package project.simpleMsg;

import java.util.concurrent.TimeUnit;

import org.apache.log4j.Logger;
import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.ExceptionEvent;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelUpstreamHandler;
import org.jboss.netty.util.Timeout;
import org.jboss.netty.util.Timer;
import org.jboss.netty.util.TimerTask;

public class SimpleMsgClientHandler extends SimpleChannelUpstreamHandler {

	private final ClientBootstrap bootstrap;
	private final Timer timer;
	// public Channel ch = null;

	private static final Logger logger = Logger
			.getLogger(SimpleMsgClientHandler.class.getName());

	public SimpleMsgClientHandler(ClientBootstrap bootstrap, Timer timer) {
		this.bootstrap = bootstrap;
		this.timer = timer;
	}

	@Override
	public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
		logger.info("Connected:\t" + e.getChannel());
		// ch = e.getChannel();

		// e.getChannel().write(
		// ChannelBuffers.copiedBuffer("Hello", Charset.forName("UTF-8")));

	}

	@Override
	public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
		// logger.info("Receive:\t" + e.getMessage().toString().length());
		// logger.info("Receive:\t"
		// + ((ChannelBuffer) e.getMessage()).toString(Charset
		// .forName("UTF-8")).length());
		// DeadClock.deadSilence(2000L);
		// e.getChannel().disconnect();
		System.out.println("Receive:\t" + e.getMessage());
	//	e.getChannel().write(e.getMessage().toString());
	}

	@Override
	public void channelDisconnected(ChannelHandlerContext ctx,
			ChannelStateEvent e) {
		logger.info("DisConnected:	" + e.getChannel());
	}

	@Override
	public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) {
		// logger.info("Closed:	" + e.getChannel());
		// ch = null;
		// waitAndReconnect();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
		// logger.error("Msg Client Error	" + e.getChannel(), e.getCause());
	}

	private void waitAndReconnect() {
		logger.warn("Sleeping for: 5s");
		timer.newTimeout(new TimerTask() {
			@Override
			public void run(Timeout timeout) throws Exception {
				// logger.info("Reconnecting");
				bootstrap.connect();
			}
		}, 5, TimeUnit.SECONDS);
	}
}
